package com.ruoyi.web.controller.mes;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.pinyin.PinYinUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.web.domain.MesCuttingGroup;
import com.ruoyi.web.domain.mes.MesMachinePaper;
import com.ruoyi.web.mapper.*;
import com.ruoyi.web.service.*;
import com.ruoyi.web.service.Impl.MesPaperService;
import com.ruoyi.web.vo.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/report")

public class ReportController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(IMesCustomService.class);
    @Resource
    private ReportService reportService;
    @Resource
    private ReportCareService reportCareService;
    @Resource
    private ReportUserService reportUserService;
    @Resource
    private ReportWorkService reportWorkService;
    @Resource
    private MesConfigMapper configMapper;
    @Resource
    private ProduceService produceService;
    @Resource
    private ProducePieceService producePieceService;
    @Resource
    private MesProducePieceMachineService producePieceMachineService;
    @Resource
    private MesMachineService mesMachineService;
    @Resource
    private MesPaperService mesPaperService;
    @Resource
    private ReportMapper reportMapper;
    @Resource
    private ProduceMapper produceMapper;
    @Resource
    private MesCuttingGroupService mesCuttingGroupService;
    @Resource
    private MesRotateService mesRotateService;
    @Resource
    private MesCoveringService mesCoveringService;
    @Resource
    private MesBindingDailyService mesBindingDailyService;

    @PostMapping(value = "/list")
    public TableDataInfo list(@RequestBody Map<String, String> params) {
        // startPage(params);
        String code = params.get("code");            // 报工单编码
        String reportDate = params.get("reportDate");// 报工日期
        String headName = params.get("headName");    // 机长
        String createBy = params.get("createBy");    // 上报人
        String type = params.get("type");            // 类型
        String status = params.get("status");        // 状态
        String machineId = params.get("machineId");        // 机台Id
        String produceNo = params.get("produceNo");        // 生产单
        String workshopName = params.get("workshopName");        //
        Report mesReport = new Report();
        mesReport.setProduceNo(produceNo);
        mesReport.setHeadName(headName);
        mesReport.setCode(code);
        mesReport.setType(type);
        mesReport.setMachineId(machineId);
        mesReport.setSearchDate(reportDate);
        mesReport.setWorkshopName(workshopName);
        if (StringUtils.isNotEmpty(status)) {
            mesReport.setStatus(Integer.parseInt(status));
        }
        //获取角色
        Long userId = SecurityUtils.getUserId();//当前登录人用户ID
        //根据用户ID判断这个这个人是否拥有新版制版角色
        String roleKey = reportMapper.selectRoleKeyBuUserId(userId);
        //        角色；
        //业务角色_印刷报工：ysje_ysbg
        //业务角色_大刀裁切组：ddcq
        //业务角色_折页报工：ywjs_zybg
        //业务角色_覆膜报工: ywje_fmbg
        //业务角色_装订报工: ywjs_zdbg1
        if (StringUtils.isNotEmpty(roleKey)) {
            //查询本人的数据
            mesReport.setCreateById(userId);
        }
        startPage(params);
        List<Report> reportList = reportMapper.selectMesReportList(mesReport);
        TableDataInfo data = getDataTable(reportList);
        return data;
    }

    @PostMapping(value = "/add")
    @Transactional
    public AjaxResult add(@RequestBody Report report) {

        if (report.getId() == null) {
            report.setId(UUID.randomUUID().toString().replace("-", ""));
            report.setCreateBy(SecurityUtils.getUsername());
            report.setCreateTime(DateUtils.getNowDate());
            Long userId = SecurityUtils.getUserId();
            report.setCreateById(userId);


            if (report.getReportCareList() != null && report.getReportCareList().size() != 0) {
                int xh = 0;
                for (ReportCare reportCare : report.getReportCareList()) {
                    xh = xh + 1;
                    String xlh = PinYinUtils.sequence(xh);//序列号
                    reportCare.setReportId(report.getId());
                    reportCare.setCode(report.getCode() + "BY" + xlh);
                    reportCare.setCreateBy(SecurityUtils.getUsername());
                    reportCare.setCreateTime(DateUtils.getNowDate());
                }
            }

        } else {
            report.setUpdateTime(DateUtils.getNowDate());
            report.setUpdateBy(SecurityUtils.getUsername());
        }

        if (report.getReportUserList() != null && report.getReportUserList().size() != 0) {
            for (ReportUser reportUser : report.getReportUserList()) {
                reportUser.setReportId(report.getId());
                reportUser.setCreateBy(SecurityUtils.getUsername());
                reportUser.setCreateTime(DateUtils.getNowDate());
            }

        }
        if (report.getReportWorkList() != null && report.getReportWorkList().size() != 0) {
            for (ReportWork reportWork : report.getReportWorkList()) {
                reportWork.setId(UUID.randomUUID().toString().replace("-", ""));
                reportWork.setReportId(report.getId());
                reportWork.setCreateBy(SecurityUtils.getUsername());
                reportWork.setCreateTime(DateUtils.getNowDate());
            }
        }
        // 上报主表机台id
        String machineId = report.getMachineId();
        MesMachine mesMachine = mesMachineService.getById(machineId);
        String machineType = mesMachine.getType();

/*        // 判断当前步骤的报工量不能大于上一步骤的报工量
        String failureMsg = MesReportWork.checkMesReportPreviousStep(report, machineType);
        if (StringUtils.isNotEmpty(failureMsg)) {
            return AjaxResult.warn(failureMsg);
        }*/


        if (report.getReportWorkList() != null && report.getReportWorkList().size() != 0) {
            List<ReportWork> reportWorkList = report.getReportWorkList();
            for (ReportWork reportWork : reportWorkList) {
                // 报工量，印多少份
                BigDecimal finishNum = reportWork.getFinishNum() == null ? new BigDecimal("0") : reportWork.getFinishNum();

                String fromType = reportWork.getFromType() == null ? "0" : reportWork.getFromType();
                // 选纸张
                if (fromType.equals("2")) {     // 白纸裁切
                    if (reportWork.getPaperId() != null) {
                        //先验证裁切组库存是否足够
                        List<MesCuttingGroup> cuttingGroups = mesCuttingGroupService.list(new QueryWrapper<MesCuttingGroup>()
                                .lambda().eq(MesCuttingGroup::getPaperId, reportWork.getPaperId()));
                        if (cuttingGroups != null && cuttingGroups.size() > 0) {
                            MesCuttingGroup cuttingGroup = cuttingGroups.get(0);
                            int resultBigDecimal = cuttingGroup.getWhiteNum().compareTo(finishNum.doubleValue());
                            if (resultBigDecimal < 0) {
                                throw new ServiceException("裁切组纸张" + reportWork.getPaperId() + "库存不足！");
                            }
                        } else {
                            throw new ServiceException("裁切组没有该纸张！");
                        }

                        //减机台裁切组白纸库存
                        mesCuttingGroupService.update(new UpdateWrapper<MesCuttingGroup>().lambda()
                                .setSql("white_num = white_num - " + finishNum)
                                .eq(MesCuttingGroup::getPaperId, reportWork.getPaperId()));

                        //加机台裁切组裁切库存
                        mesCuttingGroupService.update(new UpdateWrapper<MesCuttingGroup>().lambda()
                                .setSql("cutting_num = cutting_num + " + finishNum)
                                .eq(MesCuttingGroup::getPaperId, reportWork.getPaperId()));
                    }
                    // 白纸裁切没有累积报工量和最大允许报工量
                }
                // 选生产单
                else {

//                    //region 印刷报工可以报多次的贴，未全部报工的不改贴的状态
//                    if (report.getType().equals("1") && reportWork.getMultipleReport().equals("0")) {
//                        // 更新报工单状态 ,未审核
//                        reportService.update(new UpdateWrapper<Report>().lambda().set(Report::getStatus, 0).eq(Report::getId, report.getId()));
//
//                        return AjaxResult.success("添加成功", report.getId());
//                    }
//                    //endregion

                    //region 更改贴的状态
                    // 印刷报工必须是全部报工的,或者是裁切和折页的,才改状态
                    if ((report.getType().equals("1") && reportWork.getMultipleReport().equals("1")) || !report.getType().equals("1")) {
                        String state = "2";
                        // 更改帖数表各工艺状态
                        if (machineType.equals("2")) {//印刷机
                            producePieceService
                                    .update(new UpdateWrapper<ProducePiece>().lambda()
                                            .set(ProducePiece::getPressState, state)
                                            .eq(ProducePiece::getPieceId, reportWork.getPieceId())
                                    );
                        }
                        if (machineType.equals("6") || machineType.equals("5")) {//封面裁切
                            producePieceService
                                    .update(new UpdateWrapper<ProducePiece>().lambda()
                                            .set(ProducePiece::getTrimmingState, state)
                                            .eq(ProducePiece::getPieceId, reportWork.getPieceId())
                                    );
                        }
                        if (machineType.equals("4")) {//折页
                            producePieceService
                                    .update(new UpdateWrapper<ProducePiece>().lambda()
                                            .set(ProducePiece::getFoldState, state)
                                            .eq(ProducePiece::getPieceId, reportWork.getPieceId())
                                    );
                        }

                        ProducePiece producePiece = producePieceService.getById(reportWork.getPieceId());
                        // boolean finish = true; // 贴的每一步骤是否全部完成
                        int num = 0;
                        List<MesProducePieceMachine> list = producePieceMachineService.list(new QueryWrapper<MesProducePieceMachine>()
                                .lambda().eq(MesProducePieceMachine::getPieceId, reportWork.getPieceId()));
                        //先查询中间表是否全部完成
                        for (MesProducePieceMachine item : list) {
                            if (item.getMachineType().equals("2")) {    //印刷机
                                if (String.valueOf(producePiece.getPressState()).equals("2")) {
                                    num++;
                                }
                            } else if (item.getMachineType().equals("6") || item.getMachineType().equals("5")) {  //封面裁切
                                if (String.valueOf(producePiece.getTrimmingState()).equals("2")) {
                                    num++;
                                }
                            } else if (item.getMachineType().equals("4")) { //折页
                                if (String.valueOf(producePiece.getFoldState()).equals("2")) {
                                    num++;
                                }
                            } else if (item.getMachineType().equals("7")) {   //覆膜
                                if (String.valueOf(producePiece.getCoveringState()).equals("2")) {
                                    num++;
                                }
                            } else if (item.getMachineType().equals("3")) {   //装订
                                if (String.valueOf(producePiece.getBindingState()).equals("2")) {
                                    num++;
                                }
                            }
                        }
                        if (num == list.size()) {
                            // 更改帖数表总的状态
                            producePieceService.update(new UpdateWrapper<ProducePiece>().lambda().set(ProducePiece::getPrintStatus, "2").eq(ProducePiece::getPieceId, reportWork.getPieceId()));
                        }
                    }

                    //endregion

                }
            }

            //region 更新本次报工所选生产单状态
            //region 本次报工单筛选帖(去重)
            List<String> PieceIdList = reportWorkList.stream().map(it -> (it.getPieceId())).collect(Collectors.toList());
            Set pieceSet = new HashSet(PieceIdList);
            PieceIdList.clear();
            PieceIdList.addAll(pieceSet);
            //endregion
            if (PieceIdList.size() > 0) {
                //region 查询这些帖有多少生产单(去重)
                List<ProducePiece> maplist = producePieceService.list(new QueryWrapper<ProducePiece>().lambda().in(ProducePiece::getPieceId, PieceIdList));
                List<String> produceIds = maplist.stream().map(t -> t.getProduceId()).collect(Collectors.toList());
                Set produceIdsSet = new HashSet(produceIds);
                produceIds.clear();
                produceIds.addAll(produceIdsSet);
                //endregion

                //region 更新本次报工生产单状态 - 当前工序进行中
                for (String item : produceIds) {
                    int produceStatus = 0; // 生产单状态
                    boolean zying = false;
                    if (report.getType().equals("1")) { // 印刷报工
                        produceStatus = 6;
                        zying = true;
                    } else if (report.getType().equals("2")) { // 折页报工
                        produceStatus = 9;
                        List<Map<String, Object>> ysPieceCount = new ArrayList<>();
                        ysPieceCount = producePieceService.listMaps(new QueryWrapper<ProducePiece>().lambda()
                                .eq(ProducePiece::getProduceId, item)
                                .eq(ProducePiece::getPressState, "2")
                                .isNotNull(ProducePiece::getPressState));

                        ProducePiece piece = new ProducePiece();
                        piece.setProduceId(item);
                        piece.setMachineType(machineType);
                        Integer resultNum = produceMapper.getPieceCount(piece);
                        int countlistsum = (resultNum != null) ? resultNum : 0;

                        if (ysPieceCount.size() > 0 && ysPieceCount.size() == countlistsum) {
                            zying = true;
                        }

                    } else if (report.getType().equals("3")) { // 裁切报工
                        produceStatus = 11;
                        zying = true;
                    }
                    Produce produceCurrent = produceService.getById(item);
                    if (produceCurrent != null && zying) {
                        String produceCurrentStatus = produceCurrent.getStatus() == null ? "" : produceCurrent.getStatus();
                        if (!produceCurrentStatus.equals("17") && !produceCurrentStatus.equals("18")) {
                            produceService.update(new UpdateWrapper<Produce>().lambda().set(Produce::getStatus, produceStatus).eq(Produce::getProduceId, item));
                        }
                    }
                }
                //endregion

                //region 遍历查看生产单中是否存在当前工序未完成的帖,如果不存在更新生产单状态 - 当前工序完成
                for (String item : produceIds) {
                    List<Map<String, Object>> countlist = new ArrayList<>();
                    if (report.getType().equals("1")) { // 印刷报工
                        countlist = producePieceService.listMaps(new QueryWrapper<ProducePiece>().lambda()
                                .eq(ProducePiece::getProduceId, item)
                                .eq(ProducePiece::getPressState, "2")
                                .isNotNull(ProducePiece::getPressState));
                    } else if (report.getType().equals("2")) { // 折页报工
                        countlist = producePieceService.listMaps(new QueryWrapper<ProducePiece>().lambda()
                                .eq(ProducePiece::getProduceId, item)
                                .eq(ProducePiece::getFoldState, "2")
                                .isNotNull(ProducePiece::getFoldState));
                    } else if (report.getType().equals("3")) { // 封面裁切报工
                        countlist = producePieceService.listMaps(new QueryWrapper<ProducePiece>().lambda()
                                .eq(ProducePiece::getProduceId, item)
                                .eq(ProducePiece::getTrimmingState, "2")
                                .isNotNull(ProducePiece::getTrimmingState));
                    }

                    ProducePiece piece = new ProducePiece();
                    piece.setProduceId(item);
                    piece.setMachineType(machineType);
                    Integer resultNum = produceMapper.getPieceCount(piece);
                    int countlistsum = (resultNum != null) ? resultNum : 0;

                    if (countlist.size() > 0 && countlist.size() == countlistsum) {
                        int produceStatus = 0; // 生产单状态
                        if (report.getType().equals("1")) { // 印刷报工
                            produceStatus = 7;
                        } else if (report.getType().equals("2")) { // 折页报工
                            produceStatus = 10;
                        } else if (report.getType().equals("3")) { // 裁切报工
                            produceStatus = 12;
                        }
                        Produce produceCurrent = produceService.getById(item);
                        if (produceCurrent != null) {
                            String produceCurrentStatus = produceCurrent.getStatus() == null ? "" : produceCurrent.getStatus();
                            if (!produceCurrentStatus.equals("17") && !produceCurrentStatus.equals("18")) {
                                produceService.update(new UpdateWrapper<Produce>().lambda().set(Produce::getStatus, produceStatus).eq(Produce::getProduceId, item));
                            }
                        }

                    }
                }
                //endregion
            }
            //endregion
        }

        //region 印刷报工后分配机台
        if (report.getType().equals("1")) {
            //查询剩余工作量是否大于平张30令，卷筒300令
            List<MesMachine> mesMachines = produceMapper.getprinttask(machineId);
            if (mesMachines != null && mesMachines.size() > 0) {
                Produce p = new Produce();
                p.setSheetSizeList(mesMachine.getSize());
                p.setWorkshopId(mesMachine.getWorkshopId());
                //获取板材尺寸相同且交货日期最近的一条生产单
                List<Produce> produce = new ArrayList<>();
                //轮流分配机台
                List<MesRotate> mesRotates = mesRotateService.list(new QueryWrapper<MesRotate>()
                        .lambda().eq(MesRotate::getMachineId, machineId)
                );
                //有轮流分配机台
                if (mesRotates != null && mesRotates.size() > 0) {
                    p.setPrintColor(mesRotates.get(0).getPrintColor());
                    p.setType(mesRotates.get(0).getType());
                    p.setBreedType(mesRotates.get(0).getBreed());
                    produce = produceMapper.allocationProduceId(p);
                    if (produce != null && produce.size() > 0) {
                        //分配机台
                        produceService.AllocationMachine(produce.get(0).getProduceId());
                    }
                } else {
                    produce = produceMapper.allocationProduceId(p);
                    if (produce != null && produce.size() > 0) {
                        //分配机台
                        produceService.AllocationMachine(produce.get(0).getProduceId());
                    }
                }
            }
        }
        //endregion

        //region 生成订单编号
        Map<String, Object> map = new HashMap<>();
        map.put("columnName", "code");
        map.put("tableName", "mes_report");
        int maxNum = configMapper.getMouthMaxId(map);
        if (Objects.equals(report.getType(), "1")) {
            String code = PinYinUtils.getCodeNormal(maxNum, "YSBG");
            report.setCode(code);
        } else if (Objects.equals(report.getType(), "2")) {
            String code = PinYinUtils.getCodeNormal(maxNum, "ZYBG");
            report.setCode(code);
        } else if (Objects.equals(report.getType(), "3")) {
            String code = PinYinUtils.getCodeNormal(maxNum, "CQBG");
            report.setCode(code);
        } else if (Objects.equals(report.getType(), "4")) {
            String code = PinYinUtils.getCodeNormal(maxNum, "FMBG");
            report.setCode(code);
        } else if (Objects.equals(report.getType(), "5")) {
            String code = PinYinUtils.getCodeNormal(maxNum, "ZDBG");
            report.setCode(code);
        } else {
            String code = PinYinUtils.getCodeNormal(maxNum, "QTBG");
            report.setCode(code);
        }
        //endregion

        //region 保存报工单主子表
        reportService.saveOrUpdate(report);
        if (report.getReportCareList() != null && report.getReportCareList().size() != 0) {
            reportCareService.remove(new QueryWrapper<ReportCare>().lambda().eq(ReportCare::getReportId, report.getId()));
            reportCareService.saveBatch(report.getReportCareList());
        }
        if (report.getReportUserList() != null && report.getReportUserList().size() != 0) {
            reportUserService.remove(new QueryWrapper<ReportUser>().lambda().eq(ReportUser::getReportId, report.getId()));
            reportUserService.saveBatch(report.getReportUserList());
        }
        if (report.getReportWorkList() != null && report.getReportWorkList().size() != 0) {
            reportWorkService.remove(new QueryWrapper<ReportWork>().lambda().eq(ReportWork::getReportId, report.getId()));
            reportWorkService.saveBatch(report.getReportWorkList());
        }
        //endregion

        // 更新报工单状态 ,未审核
        reportService.update(new UpdateWrapper<Report>().lambda().set(Report::getStatus, 0).eq(Report::getId, report.getId()));
        // AjaxResult.warn()
        return AjaxResult.success("添加成功", report.getId());
    }

    @PostMapping(value = "/updateQuality")
    @Transactional
    public AjaxResult updateQuality(@RequestBody Report report) {
        // 只修改质量上报原因
        return new AjaxResult();
    }


    @PostMapping(value = "/updateStatus")
    @Transactional
    public AjaxResult updateStatus(@RequestBody Map<String, String> params) {
        String id = params.get("id");
        String status = params.get("status");

        // 上报主表机台类型
        String machineType = params.get("machineType");
        Report report = reportService.getById(id);
        // 上报主表机台id
        String machineId = report.getMachineId();
        MesMachine mesMachine = mesMachineService.getById(machineId);
        String workshopId = "";  // 车间
        String machineName = "";
        if (StringUtils.isEmpty(machineType) && mesMachine != null) {
            machineType = mesMachine.getType();
            workshopId = mesMachine.getWorkshopId();
            machineName = mesMachine.getMachineName();
        }

        if (status.equals("1")) { // 车间主任审核通过
            List<ReportWork> reportWorkList = reportWorkService.list(new QueryWrapper<ReportWork>().lambda().eq(ReportWork::getReportId, id));
            List<ReportUser> reportUserList = reportUserService.list(new QueryWrapper<ReportUser>().lambda().eq(ReportUser::getReportId, id));

            report.setReportUserList(reportUserList);
            report.setReportWorkList(reportWorkList);

            List<MesProducePieceMachine> listProducePieceMachine = new ArrayList<>();
            // 印刷报工 -- 减纸逻辑
            if (report.getType().equals("1")) {
                String targetMachine = machineId;  // 减库存的目标机台
                // 印刷报工可以报多次的贴，未全部报工的不减库存
                List<String> filterPieceId = new ArrayList<>();
                for (ReportWork reportWork : reportWorkList) {
                    if (!reportWork.getMultipleReport().equals("0")) {
                        filterPieceId.add(reportWork.getPieceId());
                    }
                }

                // 对印刷报工单中各个贴对应的纸进行分组(关联印刷单)，分组累计实际用纸令数
                String filterPieceIdStr = filterPieceId.stream().collect(Collectors.joining(","));
                log.info("测试机台库存问题,报工单编码：" + report.getCode() + ",贴:" + filterPieceIdStr);
                MesProducePieceMachine producePieceMachine = new MesProducePieceMachine();
                producePieceMachine.setPieceIds(filterPieceIdStr);
                if (machineId.equals("325eb4a641ef4d5fb1d42d275d607e21")) {    // 轮转（M700)4号机 减库存需要减 轮转（M700)3号机
                    targetMachine = "5ce9c01407214812904ebbce9c405830";
                }
                producePieceMachine.setMachineId(targetMachine);
                producePieceMachine.setReportCode(report.getCode());
                listProducePieceMachine = produceMapper.getMachinePaperTotal(producePieceMachine);

                // 按照报工的纸类型,分别减机台纸的库存
                for (MesProducePieceMachine paperItem : listProducePieceMachine) {
                    // 分别对这些纸张进行库存判断，有一个库存不足就提示，并且不减机台库存，反之减库存
                    if (paperItem.getSumPaperLing().compareTo(paperItem.getSumMachineTotal()) > 0) {
                        throw new ServiceException("当前报工单用纸量大于机台库存,用纸量" + paperItem.getSumPaperLing() + ",机台库存" + paperItem.getSumMachineTotal() + ",纸张编号:" + paperItem.getPaperNo() + ",纸张名称:" + paperItem.getPaperName());
                    }
                }


                for (MesProducePieceMachine paperItem : listProducePieceMachine) {
                    MesMachinePaper machinepaper = new MesMachinePaper();
                    machinepaper.setPaperid(paperItem.getPaperId());
                    machinepaper.setNumber(paperItem.getSumPaperLing());
                    machinepaper.setType((long) 2);
                    machinepaper.setMachineid(targetMachine);
                    log.info("测试机台库存问题,报工单编码：" + report.getCode() + ",纸张ID:" + paperItem.getPaperId() + ",机台ID:" + targetMachine + ",用纸量:" + paperItem.getSumPaperLing());
                    //更改机台库存
                    mesPaperService.updateMachinePaper(machinepaper);
                }
            }

//            // 查询有质量事故的完成工作量明细，插入到质量管理模块
//            List<ReportWork> qualityWorklist = reportWorkList.stream().filter(it -> it.getAccident().equals("1")).collect(Collectors.toList());
//            if (qualityWorklist.size() > 0) {
//                // 插入主表
//                MesQuality mesQuality = new MesQuality();
//                // 生成质量处理单id
//                mesQuality.setId(UUID.randomUUID().toString().replace("-", ""));
//
//                // 生成质量处理单编号
//                Map<String, Object> map = new HashMap<>();
//                map.put("columnName", "code");
//                map.put("tableName", "mes_quality");
//                int maxNum = configMapper.getMouthMaxId(map);
//                String code = PinYinUtils.getCodeNormal(maxNum, "ZLCL");
//
//                mesQuality.setReportId(report.getId());
//                mesQuality.setCode(code);
//                mesQuality.setMachineId(machineId);
//                mesQuality.setMachineName(report.getMachineName());
//                mesQuality.setHeadId(report.getHeadId());
//                mesQuality.setHeadName(report.getHeadName());
//                mesQuality.setStatus(1); // 未提交
//                mesQuality.setDisposeType(report.getType());
//                mesQuality.setCreateBy(SecurityUtils.getUsername());
//                mesQuality.setCreateTime(DateUtils.getNowDate());
//                // 插入质量主表
//                mesQualityService.save(mesQuality);
//
//                List<MesQualityUser> mesQualityUserList = new ArrayList<>();
//                for (ReportUser qualitytUser : reportUserList) {
//                    MesQualityUser mesQualityUser = new MesQualityUser();
//                    mesQualityUser.setQualityId(mesQuality.getId());
//                    mesQualityUser.setNo(qualitytUser.getNo());
//                    mesQualityUser.setName(qualitytUser.getName());
//                    mesQualityUser.setCreateBy(SecurityUtils.getUsername());
//                    mesQualityUser.setCreateTime(DateUtils.getNowDate());
//                    mesQualityUserList.add(mesQualityUser);
//                }
//                // 批量插入罚款人员
//                mesQualityUserService.saveBatch(mesQualityUserList);
//
//                List<MesQualityWork> mesQualityWorklist = new ArrayList<>();
//                for (ReportWork qualityWork : qualityWorklist) {
//                    MesQualityWork mesQualityWork = new MesQualityWork();
//                    mesQualityWork.setQualityId(mesQuality.getId());
//                    BeanUtils.copyProperties(qualityWork, mesQualityWork);
//                    mesQualityWork.setCreateBy(SecurityUtils.getUsername());
//                    mesQualityWork.setCreateTime(DateUtils.getNowDate());
//                    mesQualityWorklist.add(mesQualityWork);
//                }
//                // 批量插入完成工作量明细
//                mesQualityWorkService.saveBatch(mesQualityWorklist);
//            }

        }
//        // 更新报工单状态
        reportService.update(new UpdateWrapper<Report>().lambda().set(Report::getStatus, status).eq(Report::getId, id));
        return AjaxResult.success("更新成功");
    }

    @PostMapping(value = "/getById")
    public AjaxResult getById(@RequestBody Map<String, String> params) {
        String id = params.get("id");
        Report report = reportService.getById(id);
        String machineId = report.getMachineId();
        String machineType = "";
        MesMachine mesMachine = mesMachineService.getById(machineId);
        if (mesMachine != null) {
            machineType = mesMachine.getType();
        }

        List<ReportCare> reportCareList = reportCareService.list(new QueryWrapper<ReportCare>().lambda().eq(ReportCare::getReportId, report.getId()).orderByDesc(ReportCare::getCreateTime));
        List<ReportUser> reportUserList = reportUserService.list(new QueryWrapper<ReportUser>().lambda().eq(ReportUser::getReportId, report.getId()).orderByDesc(ReportUser::getCreateTime));

//        List<ReportWork> reportWorkList = reportWorkService.list(new QueryWrapper<ReportWork>().lambda().eq(ReportWork::getReportId, report.getId())
//                .orderByAsc(ReportWork::getProduceCode).orderByAsc(ReportWork::getBreed).orderByAsc(ReportWork::getLabeling));
        // // .orderByAsc(ReportWork::getBreed).orderByAsc(ReportWork::getLabeling));

        List<ReportWork> reportWorkList = reportMapper.selectMewReportWorkList(id);
        report.setReportCareList(reportCareList);
        report.setReportUserList(reportUserList);
        for (ReportWork reportWork : reportWorkList) {
            if (StringUtils.isNotEmpty(reportWork.getProduceId())) {
                List<Produce> produceList = produceService.list(new QueryWrapper<Produce>().lambda().eq(StringUtils.isNotEmpty(reportWork.getProduceId()),
                        Produce::getProduceId, reportWork.getProduceId()));
                if (produceList != null && produceList.size() > 0) {
                    reportWork.setPubNo(produceList.get(0).getPubNo());
                }

            }
        }
        report.setReportWorkList(reportWorkList);

//        // 循环查询累计上报数量 和 最大允许上报量
//        MesReportWork.selectMesReportTotalNum(report, machineId, machineType);

//        for (ReportWork reportWork : reportWorkList) {
//            // 白纸裁切查询累计上报数量
//            if (machineType.equals("5")) {
//                if (reportWork.getPaperId() != null) {
//                    MesCuttingGroup cuttingGroup = mesCuttingGroupService.getOne(new QueryWrapper<MesCuttingGroup>().lambda()
//                            .eq(MesCuttingGroup::getPaperId, reportWork.getPaperId()));
//                    if (cuttingGroup != null) {
//                        double cuttingNum = cuttingGroup.getCuttingNum() == null ? 0 : cuttingGroup.getCuttingNum();
//                        reportWork.setTotalNum(new BigDecimal(cuttingNum));
//                    }
//                }
//
//            } else { // 生产单报工查询累计上报数量
//                MesProducePieceMachine producePieceMachine = producePieceMachineService.getOne(new QueryWrapper<MesProducePieceMachine>().lambda()
//                        .eq(MesProducePieceMachine::getPieceId, reportWork.getPieceId())
//                        .eq(MesProducePieceMachine::getMachineId, machineId)
//                        .last("LIMIT 1")
//                );
//                if (producePieceMachine != null) {
//                    reportWork.setTotalNum(producePieceMachine.getTotal());
//                }
//            }
//        }

        return AjaxResult.success("查询成功", report);
    }

    @PostMapping(value = "/edit")
    @Transactional
    public AjaxResult edit(@RequestBody Report report) {
        if(StringUtils.isEmpty(report.getId())) return AjaxResult.error("未获取到主键信息");
        if(report.getReportUserList() != null && report.getReportUserList().size() > 0){
            List<ReportUser> list = reportUserService.list(new QueryWrapper<ReportUser>().eq("report_id", report.getId()));
            Map<String, String> newMap = report.getReportUserList().stream().filter(e -> StringUtils.isNotEmpty(e.getId())).collect(Collectors.toMap(ReportUser::getId, ReportUser::getId));
            for (ReportUser reportUser : list) {
                boolean isDel = true;
                if(StringUtils.isNotEmpty(reportUser.getId())){
                    if(StringUtils.isNotEmpty(newMap.get(reportUser.getId()))){
                        isDel = false;
                    }
                }
                if(isDel){
                    reportUserService.removeById(reportUser.getId());
                }
            }
            report.getReportUserList().forEach(e ->{
                e.setReportId(report.getId());
            });
            reportUserService.saveOrUpdateBatch(report.getReportUserList());
        }
        if(report.getReportWorkList() != null && report.getReportWorkList().size() > 0){
            report.getReportWorkList().forEach(e ->{
                e.setReportId(report.getId());
            });
            reportWorkService.saveOrUpdateBatch(report.getReportWorkList());
        }
        return AjaxResult.success();
    }

    @PostMapping(value = "/deleteById")
    public AjaxResult deleteById(@RequestBody Map<String, String> params) {
        String id = params.get("id");
        reportService.removeById(id);
        reportCareService.remove(new QueryWrapper<ReportCare>().lambda().eq(ReportCare::getReportId, id));
        reportUserService.remove(new QueryWrapper<ReportUser>().lambda().eq(ReportUser::getReportId, id));
        reportWorkService.remove(new QueryWrapper<ReportWork>().lambda().eq(ReportWork::getReportId, id));
        return AjaxResult.success("删除成功");
    }

    // 导出报工明细
    @PostMapping("/exportReportDetail")
    public void exportReportDetail(HttpServletResponse response, @RequestBody Report report) {
        List<ReportWork> reportList = gettReportDetailPublicWay(report, "export");
        ExcelUtil<ReportWork> util = new ExcelUtil<>(ReportWork.class);
        util.exportExcel(response, reportList, "报工明细");
    }


    @GetMapping(value = "/getReportDetail")
    public TableDataInfo getReportDetail(Report report) {
        List<ReportWork> reportList = gettReportDetailPublicWay(report, null);
        return getDataTable(reportList);
    }


    public List<ReportWork> gettReportDetailPublicWay(Report report, String type) {
        if (report.getStatus() == 0) {
            report.setStatus(-1);
        }
        List<ReportWork> reportList = new ArrayList<>();
        if (!StringUtils.isNotEmpty(type)) {
            startPage();
        }
        if (StringUtils.isNotEmpty(report.getType()) && report.getType().equals("5")) {//装订
            // 大屏调用
            if (StringUtils.isNotEmpty(report.getWorkshopId())) {
                // 获取当前时间
                Calendar cal = Calendar.getInstance();
                int year = cal.get(Calendar.YEAR);
                int month = cal.get(Calendar.MONTH) + 1;
                int day = cal.get(Calendar.DATE);
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
                    report.setBeginDate(dateFormat.parse(year + "-" + month + "-" + day + " 00:00:00"));
                    report.setEndDate(dateFormat.parse(year + "-" + month + "-" + day + " 23:59:59"));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            reportList = reportMapper.selectBindingDetailList(report);
            if (reportList.size() > 0) {
                ReportWork reportWork = reportMapper.selectBindingDetailSum(report);
                reportList.get(0).setFinishNumSum(reportWork.getFinishNumSum());
                reportList.get(0).setUsePaperSum(reportWork.getUsePaperSum());
            }
        } else if (StringUtils.isNotEmpty(report.getType()) && report.getType().equals("4")) {//覆膜
            reportList = reportMapper.selectCoverDetailList(report);
            if (reportList.size() > 0) {
                ReportWork reportWork = reportMapper.selectCoverDetailSum(report);
                reportList.get(0).setFinishNumSum(reportWork.getFinishNumSum());
                reportList.get(0).setUsePaperSum(reportWork.getUsePaperSum());
            }
        } else {
            // 大屏调用，查询印刷报工
            if (StringUtils.isNotEmpty(report.getWorkshopId()) && StringUtils.isNotEmpty(report.getType()) && report.getType().equals("1")) {
                // 获取当前时间
                Calendar cal = Calendar.getInstance();
                int year = cal.get(Calendar.YEAR);
                int month = cal.get(Calendar.MONTH) + 1;
                int day = cal.get(Calendar.DATE);
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
                    report.setBeginDate(dateFormat.parse(year + "-" + month + "-" + day + " 00:00:00"));
                    report.setEndDate(dateFormat.parse(year + "-" + month + "-" + day + " 23:59:59"));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            reportList = reportMapper.selectReportDetailList(report);
            if (reportList.size() > 0) {
                ReportWork reportWork = reportMapper.selectReportDetailSum(report);
                reportList.get(0).setFinishNumSum(reportWork.getFinishNumSum());
                reportList.get(0).setUsePaperSum(reportWork.getUsePaperSum());
            }

        }
        return reportList;
    }

    // 导出累计报工量穿透数据
    @PostMapping("/exportReportRealityLing")
    public void exportReportRealityLing(HttpServletResponse response, @RequestBody ReportWork reportWork) {
        List<ReportWork> reportList = reportMapper.selectReportDetailByRealityLing(reportWork);
        ExcelUtil<ReportWork> util = new ExcelUtil<>(ReportWork.class);
        util.exportExcel(response, reportList, "报工明细");
    }


    //根据累计报工量穿透数据
    @GetMapping(value = "/getReportDetailByRealityLing")
    public TableDataInfo getReportDetailByRealityLing(ReportWork reportWork) {
        startPage();
        List<ReportWork> reportList = reportMapper.selectReportDetailByRealityLing(reportWork);
        return getDataTable(reportList);
    }

    // 机台用纸令数查询
    @GetMapping("/getRealityLing")
    public TableDataInfo getRealityLing(ReportWork reportWork) {
        List<ReportWork> realityLing = reportService.getRealityLing(reportWork);
        return getDataTable(realityLing);
    }

    // 机台用纸令数导出
    @PostMapping("/exportRealityLing")
    public AjaxResult exportRealityLing(@RequestBody ReportWork reportWork) {
        return reportService.exportRealityLing(reportWork);
    }

    @PostMapping(value = "/repeatList")
    public TableDataInfo repeatList(@RequestBody Map<String, String> params) {
        // startPage(params);
        String code = params.get("code");            // 报工单编码
        String reportDate = params.get("reportDate");// 报工日期
        String headName = params.get("headName");    // 机长
        String createBy = params.get("createBy");    // 上报人
        String type = params.get("type");            // 类型
        String status = params.get("status");        // 状态
        String machineId = params.get("machineId");        // 机台Id
        String produceNo = params.get("produceNo");        // 生产单
        String workshopName = params.get("workshopName");        //车间
        Report mesReport = new Report();
        mesReport.setProduceNo(produceNo);
        mesReport.setHeadName(headName);
        mesReport.setCode(code);
        mesReport.setType(type);
        mesReport.setMachineId(machineId);
        mesReport.setSearchDate(reportDate);
        mesReport.setWorkshopName(workshopName);
        if (StringUtils.isNotEmpty(status)) {
            mesReport.setStatus(Integer.parseInt(status));
        }

        startPage(params);
        List<Report> reportList = reportMapper.selectRepeatReportList(mesReport);
        TableDataInfo data = getDataTable(reportList);
        return data;
    }

    @PostMapping(value = "/updateRepeatStatus")
    @Transactional
    public AjaxResult updateRepeatStatus(@RequestBody Map<String, String> params) {
        String id = params.get("id");
        String status = params.get("status");
        String type = params.get("type");
        if (type.equals("1") || type.equals("2") || type.equals("3")) {
            reportService.update(new UpdateWrapper<Report>().lambda().set(Report::getStatus, status).eq(Report::getId, id));
        } else if (type.equals("4")) {
            mesCoveringService.update(new UpdateWrapper<MesCovering>().lambda().set(MesCovering::getStatus, status).eq(MesCovering::getPid, id));
        } else if (type.equals("5")) {
            mesBindingDailyService.update(new UpdateWrapper<MesBindingDaily>().lambda().set(MesBindingDaily::getStatus, status).eq(MesBindingDaily::getId, id));
        }
        return AjaxResult.success("更新成功");
    }

}
